/**
 * 系统名称: 企业财资
 * 模块名称: repair-boot
 * 类 名 称: GzipUtils.java
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改人员:
 * 修改说明:
 * ============ ============================================
 * zhanghong 创建
 * ============ ============================================
 */
package com.mt.repair.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 *
 *
 * @author zhanghong
 * @date 2023-03-25 17:35
 */
public class GzipUtils {
    public static String TAG = GzipUtils.class.getName();
    public static Logger logger = Logger.getLogger(TAG);

    public static byte[] gzip(byte[] bArr) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bArr.length);
            GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            gZIPOutputStream.write(bArr);
            gZIPOutputStream.close();
            byteArrayOutputStream.close();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException unused) {
            logger.warning("GzipUtils: failed to gzip");
            return bArr;
        }
    }

    public static byte[] ungzip(byte[] bArr) {
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bArr);
            GZIPInputStream gZIPInputStream = new GZIPInputStream(byteArrayInputStream);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gZIPInputStream, StandardCharsets.UTF_8));
            StringBuilder sb2 = new StringBuilder();
            while (true) {
                String readLine = bufferedReader.readLine();
                if (readLine != null) {
                    sb2.append(readLine);
                } else {
                    bufferedReader.close();
                    gZIPInputStream.close();
                    byteArrayInputStream.close();
                    return sb2.toString().getBytes();
                }
            }
        } catch (IOException unused) {
            logger.warning("GzipUtils: failed to ungzip");
            return bArr;
        }
    }


    public static void main(String[] args) {
        String data = "raw data: hello world!";
        byte[] gzipByte = gzip(data.getBytes());
        String gzipData  = new String(gzipByte, StandardCharsets.UTF_8);
        logger.info("gzipData: " + gzipData);
        String ungzipData = new String(ungzip(gzipByte));
        logger.info("ungzipData: " + ungzipData);
    }
}
